<template>
  <div class="app-container">
    <div class="jcxx">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>进货退货单信息</span>
            </div>
            <div class="text item">
                <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px" label-position="left">
                  <el-row type="flex" justify="space-around" align="bottom" :gutter="16">
                    <el-col :span="10">
                      <el-form-item label="退货单号" prop="saleCode">
                        <el-input v-model="form.prCode" placeholder="自动获取系统编号" :style="{ width: '100%' }" readonly ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="退货日期" prop="saleTime">
                        <el-date-picker v-model="form.prTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }" placeholder="请选择"></el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row type="flex" justify="space-around" align="bottom" :gutter="16">
                    <el-col :span="10">
                      <el-form-item label="进货单号" prop="customer">
                        <el-input v-model="form.phCode" placeholder="进货单号" :style="{ width: '100%' }"></el-input>
                        <span class="三点" @click="selectPurchaseCodes()" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%);">
                          &#x2022;&#x2022;&#x2022;
                        </span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="供应商" prop="contacts">
                        <el-input v-model="form.supplier" placeholder="请输入供应商" :style="{ width: '100%' }" readonly></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-dialog
                    title="选择进货单"
                    :visible.sync="checkIn"
                    width="50%"
                    :before-close="handleClose">
                  <span>
                    <el-form :model="queryParams2" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                      <el-form-item label="货品单号" prop="phCode">
                        <el-input
                          v-model="queryParams2.phCode"
                          placeholder="请输入货品单号"
                          clearable
                          @keyup.enter.native="handleQuery"
                        />
                      </el-form-item>
                      <el-form-item label="单位" prop="unit">
                        <el-select v-model="queryParams2.phState" placeholder="请选择单据状态" clearable>
                          <el-option
                            v-for="dict in dict.type.py_status"
                            v-if="['2','3'].includes(dict.value)"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery2">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery2">重置</el-button>
                      </el-form-item>
                    </el-form>
                  </span>
                    <el-table
                      :data="inrejectedList"    style="margin-top: 20px; width: 100%"
                      @selection-change="handleSelectionChange2"
                    >
                      <el-table-column
                        type="selection"
                        width="55"
                      >
                      </el-table-column>
                      <el-table-column
                        prop=""
                        label="序号"
                        width="80"
                      >
                        <template slot-scope="scope">
                          {{ scope.$index + 1 }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="phCode"
                        label="进货订单"
                        width="180"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="phState"
                        label="单据状态"
                      >
                        <template slot-scope="scope">
                          <dict-tag :options="dict.type.py_status" :value="scope.row.phState"/>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="phDate"
                        label="进货日期"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="supplier"
                        label="供应商"
                        width="120"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="deptName"
                        label="进货部门"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="phPerson"
                        label="进货人"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="goodsNum"
                        label="货品数量"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="goodsMoney"
                        label="进货金额"
                      >
                      </el-table-column>
                    </el-table>
                    <pagination
                      v-show="total2>0"
                      :total="total2"
                      :page.sync="queryParams2.pageNum"
                      :limit.sync="queryParams2.pageSize"
                      @pagination="getDetails2"
                    />
                    <span slot="footer" class="dialog-footer">
                  <el-button @click="checkIn = false">取 消</el-button>
                  <el-button type="primary" @click="AddOdSaleDetails2">确 定</el-button>
                  </span>
                  </el-dialog>
                  <el-row type="flex" justify="space-around" align="bottom" :gutter="16">
                    <el-col :span="10">
                      <el-form-item label="联系人" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入联系人" :style="{ width: '100%' }" readonly></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="联系方式" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入联系方式" :style="{ width: '100%' }" readonly></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row type="flex" justify="space-around" align="bottom" :gutter="16">
                    <el-col :span="10">
                      <el-form-item label="进货部门" prop="salePerson">
                        <el-input v-model="form.phDept" placeholder="请输入进货部门" :style="{ width: '100%' }" readonly></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="进货人" prop="salePerson">
                        <el-input v-model="form.phPerson" placeholder="请输入退货部门" :style="{ width: '100%' }" readonly></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row type="flex" justify="space-around" align="bottom" :gutter="16">
                    <el-col :span="20">
                      <el-form-item label="退货原因" prop="saleRemark">
                        <el-input v-model="form.rejectedReason" placeholder="请输入退货部门" :style="{ width: '100%' }"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="0.4">
                    </el-col>
                  </el-row>
                  <el-row type="flex" justify="space-around" align="bottom" :gutter="16">
                    <el-col :span="20">
                      <el-form-item label="备注" prop="saleRemark">
                        <el-input v-model="form.remark" type="textarea" placeholder="请输入" :maxlength="1000" :autosize="{ minRows: 4, maxRows: 10 }" :style="{ width: '100%' }"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="0.4">
                    </el-col>
                  </el-row>
                </el-form>
            </div>
        </el-card>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>退货货品明细</span>
            </div>
            <div class="text item">
                <span>
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetails">添加</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOdSaleDetails">删除</el-button>
                </span>
                <!--添加明细对话框-->
              <el-dialog
                  title="添加货品"
                  :visible.sync="dialogVisible"
                  width="50%"
                  :before-close="handleClose">
                  <span>
                    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                      <el-form-item label="货品单号" prop="phCode">
                        <el-input
                          v-model="queryParams.productCode"
                          placeholder="请输入货品单号"
                          clearable
                          @keyup.enter.native="handleQuery"
                        />
                      </el-form-item>
                      <el-form-item label="单位" prop="unit">
                        <el-select v-model="queryParams.unit" placeholder="请选择单位" clearable>
                          <el-option
                            v-for="dict in dict.type.py_product_unit"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                      </el-form-item>
                    </el-form>
                  </span>
                <el-table
                  :data="tableData"    style="margin-top: 20px; width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column
                    type="selection"
                    width="55"
                  >
                  </el-table-column>
                  <el-table-column
                    prop=""
                    label="序号"
                    width="80"
                  >
                    <template slot-scope="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="productCode"
                    label="货品编号"
                    width="180"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="productName"
                    label="货品名称"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="productModel"
                    label="规格型号"
                  >
                  </el-table-column>
                  <el-table-column
                    prop=""
                    label="单位"
                  >
                    <template slot-scope="scope">
                      <dict-tag :options="dict.type.py_product_unit" :value="scope.row.unit"/>
                    </template>

                  </el-table-column>
                  <el-table-column
                    prop="price"
                    label="退货单价"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="productNum"
                    label="进货数量"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="alredlyrejectedNum"
                    label="已退货数量"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="inPrice"
                    label="进货金额"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="quantityReceived"
                    label="已入库"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="quantityPending"
                    label="未入库"
                  >
                  </el-table-column>
                </el-table>
                <pagination
                  v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getDetails"
                />
                  <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="AddOdSaleDetails">确 定</el-button>
                  </span>
              </el-dialog>
                <el-table ref="odRejectedDetailsList" :data="odRejectedDetailsList" style="width: 100%;margin-top: 10px" @selection-change="handleOdPurchaseDetailsSelectionChange" >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column fixed prop="index" label="序号" width="50"></el-table-column>
                    <el-table-column fixed prop="productName" label="货品名称" width="150">
<!--                        <template slot-scope="scope">
                            <el-input v-model="scope.row.productName" placeholder="请输入货品名称" readonly></el-input>
                        </template>-->
                    </el-table-column>
                    <el-table-column fixed prop="productCode" label="货品编码" width="180">
<!--                        <template slot-scope="scope">
                            <el-input v-model="scope.row.productCode" placeholder="请输入货品编码" readonly></el-input>
                        </template>-->
                    </el-table-column>
                    <el-table-column prop="productType" label="货品类型" width="150">
<!--                      <template slot-scope="scope">
                        <el-input v-model="scope.row.productType" placeholder="请输入货品类型" readonly></el-input>
                      </template>-->
                    </el-table-column>
                    <el-table-column prop="productModel" label="规则型号" width="150">
<!--                        <template slot-scope="scope">
                            <el-input v-model="scope.row.productModel" placeholder="请输入规则型号" readonly></el-input>
                        </template>-->
                    </el-table-column>
                    <el-table-column prop="unit" label="单位" width="50">
                      <template slot-scope="scope">
                        <dict-tag :options="dict.type.py_product_unit" :value="scope.row.unit"/>
                      </template>
                    </el-table-column>
                    <el-table-column prop="inNum" label="进货数量" width="150">
<!--                        <template slot-scope="scope">
                            <el-input v-model="scope.row.inNum" placeholder="请输入进货数量" readonly></el-input>
                        </template>-->
                    </el-table-column>
                  <el-table-column prop="alreadyNum" label="已入库" width="150">
<!--                    <template slot-scope="scope">
                      <el-input v-model="scope.row.alreadyNum" placeholder="" readonly></el-input>
                    </template>-->
                  </el-table-column>
                  <el-table-column prop="notyetNum" label="未入库" width="150">
                    <template slot-scope="scope">
<!--                      <el-input v-model="scope.row.notyetNum" placeholder="" readonly></el-input>-->
                      {{scope.row.inNum-scope.row.alreadyNum}}
                    </template>
                  </el-table-column>
                  <el-table-column v-if="this.p==null" prop="alredlyrejectedNum" label="已退货数量" width="150">
                  </el-table-column>
                  <el-table-column v-if="this.p!=null" prop="alreadyoutnum" label="已退货数量" width="150">
                  </el-table-column>
                    <el-table-column prop="rejectedNum" label="本次退货数量" width="150">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.rejectedNum" placeholder="请输入退货数量"  type="number"  :min="0"  @input="validateInput"  @change="validateProductNum(scope.row)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="inPrice" label="进货单价" width="150">
<!--                        <template slot-scope="scope">
                            <el-input v-model="scope.row.inprice" placeholder="请输入销售单价"></el-input>
                        </template>-->
                    </el-table-column>
                    <el-table-column prop="rejectedPrice" label="退货金额" width="150">
<!--                      <template slot-scope="scope">
                        <el-input v-model="scope.row.rejectedPrice" placeholder=""></el-input>
                      </template>-->
                      <template slot-scope="scope">
                        {{scope.row.inPrice*scope.row.rejectedNum}}
                      </template>-->
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" width="200">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
<!--          <el-table :data="odPurchaseDetailsList" style="width: 100%;margin-top: 10px" @selection-change="handleOdPurchaseDetailsSelectionChange">
            &lt;!&ndash; ...表格列 &ndash;&gt;
          </el-table>-->
          <div class="total-row">
            <span>合计：货品种类 {{ totalProductCategory }}，货品数量 {{ totalProductQuantity }}，总金额 {{ totalAmount }}</span>
          </div>
        </el-card>
        <el-card class="box-card">
              <div slot="header" class="clearfix">
                  <span>上传附件</span>
              </div>
              <div class="text item">
                <el-upload
                  class="upload-demo"
                  :action="uploadImgUrl"
                :on-change="uploadChange"
                :file-list="fileList"
                :before-upload="beforeUpload"
                :headers="headers"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持上传doc, pdf, rar等格式，单个文件最大200MB</div>
                </el-upload>
              </div>
          </el-card>
        <el-footer class="fixed-footer">
            <el-button type="primary" @click="submitForm" >保存</el-button>
            <el-button @click="cancel">关闭</el-button>
        </el-footer>
    </div>
  </div>
</template>

<script>
import {findCustomer} from "@/api/customers/customers";
import {
  selectAllSysDept,
  selectAllSysDeptByID,
  selectUserById,
  selectPurchase,
  selectByPhCode
} from "@/api/purchase/purchase"
import {addInrejected, getCode, getInrejected, selectPurchaseRejectProduct, updateInrejected,selectByCode} from "@/api/inrejected/inrejected"
import { getToken } from "@/utils/auth";
import inrejected from "@/views/wms/inrejected/inrejected/index.vue";
export default {
  name: "Inrejected",
  computed: {
    inrejected() {
      return inrejected
    }
  },
  dicts: ['py_product_unit','py_status'],
    data() {
        return {
            form: {
                prId: '',
                prCode: '',
                prState: '',
                prTime: '',
                phCode: '',
                supplier: '',
                contacts: '',
                phone: '',
                phDept: '',
                phPerson: '',
                rejectedNum: '',
                rejectedMoney: '',
                rejectedReason: '',
                remark: '',
                isDel: '',
                number:undefined,
                codeId:undefined,
                odRejectedDetailsList:[],
                saleNum: 0, // 货品数量合计
                saleMoney:undefined,
                fileList:[]
            },
          odRejectedDetailsList: [
                // 示例数据
            ],
            rules: {
                prCode: [{ required: true, message: '请输入单号', trigger: 'blur' }],
                prTime: [{ required: true, message: '请选择退货日期', trigger: 'change' }],
                phCode: [{ required: true, message: '请选择进货订单', trigger: 'change' }]
            },
          selectedValue: [],
          cascaderOptions: [],
          cascaderProps: {
            value: undefined,
            label: undefined,
            children: undefined,
            checkStrictly: true // 允许非叶子节点的选项被选择
          },
          // 添加明细对话框
          dialogVisible: false,
          checkIn: false,
          //查询参数
          queryParams:{
              pageNum: 1,
              pageSize: 10,
              phCode:undefined,
              productCode:undefined,
              unit:undefined
          },
          queryParams2:{
            pageNum: 1,
            pageSize: 10,
            phCode:undefined,
            phState:undefined
          }
          ,
          // 显示搜索条件
          showSearch: true,
          tableData:[],
          inrejectedList:[],
          customerVlaue:[],
          UserValue:[],
          selectedRows:[],
          selectedRows2:[],
          // 总条数
          total: 0,
          total2:0,
          UnitValue:[],
          totalProductCategory: 0, // 货品种类合计
          totalProductQuantity: 0, // 货品数量合计
          totalAmount: 0.00, // 总金额合计
          uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload",
          headers: {
            Authorization: "Bearer " + getToken()
          },
          fileList: [], // 已上传的文件列表
          p:undefined,
          isClick: true
        };
    },
    created() {
      this.fetchItems();
      findCustomer().then(response => {
        console.log("findCustomer",response)
        this.customerVlaue=response;
      });
      const purchaseId = this.$route.query.id;
      this.p=purchaseId;
      if (purchaseId==null){
      //  alert("新增")
        getCode(7).then(response => {
          console.log(response);
          this.form.prCode=response.sequence;
          this.form.number=response.number;
          this.form.codeId=response.codeId;
        });
      }else {
        this.rest();
    //    alert("进来了吗")
        getInrejected(purchaseId).then(response => {
         console.log("修改",response)
         this.form = response.data;
           this.odRejectedDetailsList = response.data.odRejectedDetailsList.map((item, index) => ({
             ...item,
             index: index + 1
           }));
           // 合并新旧文件列表
           this.fileList = [...response.data.fileList.flat().map(file => ({
             name: file.fileName,
             url: file.filePath,
             size:file.size
           })), ...this.fileList];
     });
      }
    }
  ,
    methods: {
      selectPurchaseCodes(){
        this.checkIn=true;
        this.getDetails2();
      },
      validateProductNum(row){
        /*if (Number(row.rejectedNum) > Number(row.inNum-row.alredlyrejectedNum)) {
          this.$message.warning('输入的数量不能大于可退货数量');
          row.rejectedNum = Number(row.inNum-row.alredlyrejectedNum); // 将输入值设置为库存数量
        }else*/
        if(Number(row.rejectedNum)>Number(row.alreadyNum)){
          this.$message.warning('输入的数量不能大于可退货数量');
          row.rejectedNum = Number(row.alreadyNum); // 将输入值设置为库存数量
        }
        console.log("shudu",row)
        if(Number(row.rejectedNum)>Number(row.alreadyNum-row.alredlyrejectedNum)){
          this.$message.warning('输入的数量不能大于可退货数量');
          row.rejectedNum = Number(row.alreadyNum-row.alredlyrejectedNum); // 将输入值设置为库存数量
        }
        if(Number(row.rejectedNum)>Number(row.alreadyNum-row.alreadyoutnum)){
          this.$message.warning('输入的数量不能大于可退货数量');
          row.rejectedNum = Number(row.alreadyNum-row.alreadyoutnum); // 将输入值设置为库存数量
        }
      },
      rest(){
        this.form={
          saleCode: '',
          saleState: '',
          saleTime: '',
          customer: '',
          contacts: '',
          phone: '',
          saleDept: '',
          salePerson: '',
          saleRemark: '',
          number:undefined,
          codeId:undefined,
          odRejectedDetailsList:[],
          goodsNum: 0, // 货品数量合计
          goodsMoney:undefined,
          fileList:[]
          }
        this.resetForm("form");
      },
      getDetails2(){
        console.log("this.queryParams2",this.queryParams2)
        selectPurchase(this.queryParams2).then(response => {
          console.log("nihaos", response);
          this.inrejectedList = response.rows;
          this.total2 = response.total;
        }).catch(error => {
          console.error("Error:", error);
        });
      },
      getDetails(){
        this.queryParams.phCode=this.form.phCode;
       // alert(this.queryParams.phCode)
        selectPurchaseRejectProduct(this.queryParams).then(response => {
          console.log("tableData", response);
          this.tableData = response.rows;
          this.total = response.total;
        }).catch(error => {
          console.error("Error:", error);
        });
      },
      handleSelectionChange(selection) {
        // 更新选中的行
        // 初始化一个新数组来存储选中的行，但不包含库存为0的商品
        const newSelectedRows = [];
        const invalidSelections = []; // 用于存储库存为0的商品信息

        // 遍历传入的selection数组
        selection.forEach(row => {
          // 检查入库数量是否为0
          if (row.alreadyNum === 0) {
            // 如果库存为0，将其添加到invalidSelections数组中，并给出提示
            invalidSelections.push(row);
          } else {
            // 如果库存不为0，将其添加到newSelectedRows数组中
            newSelectedRows.push(row);
          }
        });

        // 更新选中的行，只包含库存不为0的商品
        this.selectedRows = newSelectedRows;

        // 如果有库存为0的商品被尝试选择，给出提示
        if (invalidSelections.length > 0) {
          this.$message.warning('以下商品库存不足，请选择其他商品：\n' + invalidSelections.map(item => item.productName).join(', '));
        }

        console.log('Selected rows:', this.selectedRows);
      },
      handleSelectionChange2(selection){
       /* console.log("选中",selection)
        let rejectNum=0;
        let canOutNum=0;
        let time=null;
        selectByCode(selection[0].phCode).then(re=>{
          console.log("rejectNum",re)
          rejectNum=re;
        })
        let currentDate = new Date();
        alert(currentDate)
        selectByPhCode(selection[0].phCode).then(re=>{
          console.log("canOutNum",re)
          canOutNum=re.already_num;
          time=re.create_time;
        })
        alert(time)
        if(Number(rejectNum)>=Number(canOutNum)){
          this.$message.warning('该进货单已完成退货,无法选择');
          return;
        }else {
          this.selectedRows2=selection;
        }*/
        console.log("选中", selection);
        let rejectNum = 0;
        let canOutNum = 0;
        let time = null;
        let currentDate = new Date();

        // 合并两个异步请求，确保它们都完成后再进行后续操作
        Promise.all([
          selectByCode(selection[0].phCode),
          selectByPhCode(selection[0].phCode)
        ]).then(results => {
          const [rejectResult, outResult] = results;

          console.log("rejectNum", rejectResult);
          console.log("canOutNum", outResult);

          rejectNum = rejectResult;
          canOutNum = outResult.already_num;
          time = outResult.create_time;

          // 计算七天后的时间
          let createTime = new Date(time);
          let sevenDaysLater = new Date(createTime);
          sevenDaysLater.setDate(sevenDaysLater.getDate() + 7);
          // 判断条件
          if (Number(rejectNum) >= Number(canOutNum)) {
            this.$message.warning('该进货单已完成退货,无法选择');
          } else if (currentDate > sevenDaysLater) {
            this.$message.warning('该进货单已超过七天,无法选择');
          } else {
            this.selectedRows2 = selection;
          }
        }).catch(error => {
          console.error("Error fetching data:", error);
          this.$message.error('数据获取失败,请稍后再试');
        });
      },
      handleAddDetails() {
          this.dialogVisible=true;
          this.getDetails();
        },
      handleDeleteOdSaleDetails() {
          const selectedRows = this.$refs.odRejectedDetailsList.selection;
          if (selectedRows.length === 0) {
            this.$message.warning('请先选择要删除的行');
            return;
          }

          // 创建一个标识符集合，用于快速查找
          const identifiersToDelete = new Set(selectedRows.map(row => `${row.productCode}-${row.productModel}`));

          // 遍历 this.odRejectedDetailsList，移除匹配的行
          this.odRejectedDetailsList = this.odRejectedDetailsList.filter(item => {
            const identifier = `${item.productCode}-${item.productModel}`;
            return !identifiersToDelete.has(identifier);
          });

          // 重新计算索引
          this.odRejectedDetailsList.forEach((item, index) => {
            item.index = index + 1;
          });

          this.calculateTotals(); // 更新合计
        },
      AddOdSaleDetails2(){
        console.log("selectedRows2",this.selectedRows2)
        if (this.selectedRows2.length>=2){
          this.$message.warning('一次只能选择一个订单');
          return;
        }
        this.checkIn=false;
        for (let i = 0; i < this.selectedRows2.length; i++) {
          const row = this.selectedRows2[i];
          this.form.phCode=row.phCode;
          this.form.supplier=row.supplier;
          this.form.contacts=row.contacts;
          this.form.phone=row.phone;
          this.form.phDept=row.deptName;
          this.form.phPerson=row.phPerson;

        }

      },
      AddOdSaleDetails(){
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择商品');
          return;
        }
        this.dialogVisible = false

        for (let i = 0; i < this.selectedRows.length; i++) {
          const row = this.selectedRows[i];
          console.log("row",row)
          const identifier = `${row.productCode}-${row.productModel}-${row.warehouseName}-${row.locationName}`;

          let existingItem = this.odRejectedDetailsList.find(item => item.productCode === row.productCode && item.productModel === row.productModel && item.warehouseName === row.warehouseName && item.locationName === row.locationName);

          if (existingItem) {
            existingItem.productNum = Number(existingItem.productNum) + 1;
          } else {
            this.odRejectedDetailsList.push({
              index: this.odRejectedDetailsList.length + 1,
              productName: row.productName,
              productCode: row.productCode,
              productModel: row.productModel,
              unit: row.unit,
              productType: row.productType,
              inNum:row.productNum,
              alreadyNum:row.quantityReceived,
              notyetNum: row.quantityPending,
              alredlyrejectedNum:row.alredlyrejectedNum,
              rejectedNum: 1,
              inPrice: row.price,
              remark: '',
              isDel: 0
            });
          }
        }
        console.log("odRejectedDetailsList",this.odRejectedDetailsList)
        this.calculateTotals(); // 更新合计

      },
        submitForm() {
          if (this.odRejectedDetailsList.length === 0){
            this.$message.warning('请选择该进货单要退货的商品');
            return;
          }
          if (!this.isClick) {
            this.$message.warning('请勿重复提交');
            return;
          }
          this.isClick = false;
            this.$refs.form.validate(valid => {
                if (valid) {
                  this.form.odRejectedDetailsList = this.odRejectedDetailsList;
                  this.form.rejectedNum=this.totalProductQuantity;
                  this.form.rejectedMoney=this.totalAmount;
                  console.log("fileList",this.fileList)
                  this.form.fileList=this.fileList;
                  this.form.prState='0'
                  this.form.isDel='0'
                  // 将 phId 转换为字符串
                  const phIdStr = String(this.form.prId);
                 // alert(phIdStr)
                  if (phIdStr != null && phIdStr.trim() !== "") {
                    //alert("修改")
                    updateInrejected(this.form).then(response => {
                      this.$modal.msgSuccess("修改成功");
                      this.$router.push( {path:'/wms/inrejected/inrejected/find'});
                      this.isClick = true; // 请求成功，允许再次提交
                    }).catch(error => {
                      this.isClick = true; // 请求失败，允许再次提交
                    });
                  }else {
                    console.log("新增",this.form)
                  //  alert("新增")
                    addInrejected(this.form).then(response=>{
                      console.log("addInrejected",response)
                      this.$message.success('保存成功');
                      this.$router.push( {path:'/wms/inrejected/inrejected/find'});
                      this.isClick = true; // 请求成功，允许再次提交
                    }).catch(error => {
                      this.isClick = true; // 请求失败，允许再次提交
                    });
                  }
                } else {
                  this.isClick = true; // 请求失败，允许再次提交
                    this.$message.error('请检查表单信息');
                }
            });
        },
        cancel() {
            this.$emit('update:visible', false);
            this.rest();
          this.$router.push( {path:'/wms/inrejected/inrejected/find'});
        },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getDetails();
      },
      /** 搜索按钮操作 */
      handleQuery2() {
        this.queryParams2.pageNum = 1;
        this.getDetails2();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      resetQuery2() {
        this.resetForm("queryForm");
        this.handleQuery2();
      },
      async fetchItems() {
        try {
          const response = await selectAllSysDept();
          console.log('Response from findSelect:', response);
          if (Array.isArray(response)) {
            this.cascaderOptions = await this.convertToCascaderOptions(response);
            console.log('Converted cascaderOptions:', this.cascaderOptions);
          } else {
            console.error('Expected an array, but got:', response);
          }
        } catch (error) {
          console.error('Error fetching items:', error);
        }
      },
      async convertToCascaderOptions(data) {
        if (!Array.isArray(data)) {
          console.error('Expected an array, but got:', data);
          return [];
        }

        // 创建一个映射，用于快速查找父项
        const itemMap = new Map(data.map(item => [item.deptId, item]));
        // 创建一个数组，用于存储顶级项
        const topLevelItems = [];

        data.forEach(async (item) => {
          if (item.parentId === 0) {
            // 顶级项直接添加到 topLevelItems
            topLevelItems.push(await this.createOption(item));
          } else {
            // 非顶级项，尝试找到其父项并添加到 children 数组
            const parentItem = itemMap.get(item.parentId);
            if (parentItem) {
              const childItem = await this.createOption(item);
              if (parentItem.children) {
                parentItem.children.push(childItem);
              } else {
                parentItem.children = [childItem];
              }
            }
          }
        });

        return topLevelItems;
      },
      async createOption(item) {
        return {
          value: item.deptId,
          label: item.deptName,
          children: await this.fetchChildren(item.deptId)
        };
      },
      async fetchChildren(parentId) {
        try {
          const response = await selectAllSysDeptByID(parentId);
          console.log('Response from findParent:', response);
          if (Array.isArray(response)) {
            return Promise.all(response.map(async (item) => {
              return {
                value: item.deptId,
                label: item.deptName,
                children: await this.fetchChildren(item.deptId)
              };
            }));
          } else {
            console.error('Expected an array, but got:', response);
            return [];
          }
        } catch (error) {
          console.error('Error fetching children:', error);
          return [];
        }
      },
      handleChange(value) {
        console.log('Selected:', value);
        const currentSelectedValue = value[value.length - 1];
        console.log('Current Selected:', currentSelectedValue);
      //  alert(currentSelectedValue);
        this.form.saleDept=currentSelectedValue;
        selectUserById(currentSelectedValue).then(response => {
          console.log("用户",response)
          this.UserValue=response;
          })
      },
      calculateTotals() {
        /*this.totalProductCategory = this.odPurchaseDetailsList.length; // 假设货品种类由不同的货品编号表示
        this.totalProductQuantity = this.odPurchaseDetailsList.reduce((sum, item) => sum + item.productNum, 0);
        this.totalAmount = this.odPurchaseDetailsList.reduce((sum, item) => sum + (item.productNum * item.price), 0);*/
        let productCategories = new Set();
        let totalQuantity = 0;
        let totalAmount = 0;

        this.odRejectedDetailsList.forEach(item => {
          console.log("item",item)
          productCategories.add(`${item.productCode}-${item.productModel}`);
          totalQuantity += Number(item.rejectedNum || 0);
          totalAmount += (Number(item.rejectedNum || 0) * Number(item.inPrice || 0));
        });

        this.totalProductCategory = productCategories.size;
        this.totalProductQuantity = totalQuantity;
        this.totalAmount = totalAmount.toFixed(2);
      },
      handleOdPurchaseDetailsSelectionChange(selection) {
        this.selectedRows = selection;
      },
      uploadChange(file, fileList) {
        this.fileList = fileList;
      },
      beforeUpload(file) {
        // 定义允许的文件类型
        const allowedTypes = ['application/msword', 'application/pdf', 'application/x-rar-compressed','application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        // 检查文件类型是否在允许的类型中
        const isAllowedType = allowedTypes.includes(file.type);
        // 检查文件大小是否不超过200MB (200 * 1024 * 1024 bytes)
        const isLt200M = file.size <= 200 * 1024 * 1024;

        if (!isAllowedType) {
          this.$message.error('上传文件只能是 doc, pdf, rar 格式!');
        }
        if (!isLt200M) {
          this.$message.error('上传文件大小不能超过 200MB!');
        }
        return isAllowedType && isLt200M;
      },
      validateInput(value) {
        if (!/^\d*$/.test(value)) {
          // 如果输入不是数字，则将其设置为空字符串或之前的有效值
          this.$message.warning('只能输入数字');
          // 移除所有非数字字符
        }
      }
    },
  watch:{
    odRejectedDetailsList: {
      deep: true,
      handler() {
        this.calculateTotals();
      },
    },
  }
};
</script>

<style scoped>
/*
.app-container {
    position: relative; !* 确保相对定位，以便内部元素可以绝对定位 *!
    width: 100%;
    height: 100vh; !* 视口高度，确保容器足够大 *!
    overflow: hidden; !* 隐藏溢出 *!
}
*/

.jcxx {
    margin: 20px;
    position: absolute; /* 绝对定位 */
    top: 50px; /* 假设头部高度为50px */
    bottom: 60px; /* 假设底部高度为60px */
    left: 0;
    right: 0;
    overflow-y: auto; /* 允许垂直滚动 */
}

.box-card {
    margin-bottom: 20px;
}

.fixed-header, .fixed-footer {
    position: fixed;
    width: 100%;
    background: #fff;
    z-index: 10; /* 确保在内容之上 */
}

.fixed-header {
    top: 0;
    padding: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.fixed-footer {
    bottom: 0;
    padding: 10px;
  margin-left: 550px;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: center;
}

.el-cascader {
  width: 550px;
}

select {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

option {
  padding: 5px;
}

三点 {
  cursor: pointer;
  margin-left: 5px;
}
</style>
